const api = require('../../utils/api')
const { safeGet, formatTime } = require('../../utils/data-validator')
const { httpErrorHandler } = require('../../utils/http-error-handler')
const app = getApp()

Page({
  data: {
    activeTab: 'my',
    couponStatus: 'unused',
    loading: false,
    
    // 我的优惠券
    myCoupons: [],
    allMyCoupons: [],
    
    // 抢红包
    platformCoupons: [],
    storesWithCoupons: [],
    
    // 抢红包成功弹窗
    showSuccessModal: false,
    grabbedCoupon: {}
  },

  onLoad() {
    this.loadData()
  },

  onShow() {
    if (this.data.activeTab === 'my') {
      this.loadMyCoupons()
    }
  },

  // 加载数据
  async loadData() {
    this.setData({ loading: true })
    
    try {
      if (this.data.activeTab === 'my') {
        await this.loadMyCoupons()
      } else {
        await this.loadGrabCoupons()
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      httpErrorHandler.showErrorToast(error)
    } finally {
      this.setData({ loading: false })
    }
  },

  // 切换标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
    this.loadData()
  },

  // 补全优惠券数据
  completeCouponData(couponData) {
    return {
      id: safeGet(couponData, 'id', Date.now()),
      userId: safeGet(couponData, 'userId', 1),
      couponId: safeGet(couponData, 'couponId', null),
      status: safeGet(couponData, 'status', 'UNUSED'),
      claimedAt: safeGet(couponData, 'claimedAt', new Date()),
      usedAt: safeGet(couponData, 'usedAt', null),
      expired: safeGet(couponData, 'expired', false),
      coupon: {
        id: safeGet(couponData, 'coupon.id', null),
        name: safeGet(couponData, 'coupon.name', '优惠券'),
        description: safeGet(couponData, 'coupon.description', '暂无描述'),
        amount: safeGet(couponData, 'coupon.amount', 0),
        minAmount: safeGet(couponData, 'coupon.minAmount', 0),
        storeId: safeGet(couponData, 'coupon.storeId', null),
        storeName: safeGet(couponData, 'coupon.storeName', '全平台通用'),
        validTo: safeGet(couponData, 'coupon.validTo', new Date()),
        ...safeGet(couponData, 'coupon', {})
      },
      ...couponData
    }
  },

  // 加载我的优惠券
  async loadMyCoupons() {
    try {
      // 先从本地存储读取
      const localCoupons = wx.getStorageSync('myCoupons') || []
      
      // 如果本地有数据，使用本地数据，否则使用模拟数据
      let myCoupons = localCoupons.length > 0 ? localCoupons : this.generateMockMyCoupons()
      
      // 补全数据结构
      myCoupons = myCoupons.map(item => this.completeCouponData(item))
      
      // 检查过期状态
      myCoupons = myCoupons.map(item => ({
        ...item,
        expired: new Date(item.coupon.validTo) < new Date()
      }))
      
      // 保存到本地存储
      if (localCoupons.length === 0) {
        wx.setStorageSync('myCoupons', myCoupons)
      }
      
      this.setData({
        allMyCoupons: myCoupons,
        myCoupons: this.filterMyCoupons(myCoupons, this.data.couponStatus)
      })
      
      console.log('优惠券数据加载完成:', myCoupons.length)
      
    } catch (error) {
      console.error('加载我的优惠券失败:', error)
      httpErrorHandler.showErrorToast(error, {
        showModal: false,
        duration: 2000
      })
    }
  },

  // 生成模拟优惠券数据
  generateMockMyCoupons() {
    return [
      {
        id: 1,
        userId: 1,
        couponId: 1,
        status: 'UNUSED',
        claimedAt: new Date(),
        expired: false,
        coupon: {
          id: 1,
          name: '满减优惠券',
          description: '新用户专享优惠',
          amount: 10,
          minAmount: 50,
          storeId: null,
          validTo: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
        }
      },
      {
        id: 2,
        userId: 1,
        couponId: 2,
        status: 'UNUSED',
        claimedAt: new Date(),
        expired: false,
        coupon: {
          id: 2,
          name: '麦当劳专享券',
          description: '限麦当劳使用',
          amount: 5,
          minAmount: 30,
          storeId: 1,
          storeName: '麦当劳',
          validTo: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)
        }
      },
      {
        id: 3,
        userId: 1,
        couponId: 3,
        status: 'USED',
        claimedAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
        usedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
        expired: false,
        coupon: {
          id: 3,
          name: '免配送费券',
          description: '免配送费优惠',
          amount: 3,
          minAmount: 20,
          storeId: null,
          validTo: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000)
        }
      }
    ]
  },

  // 加载抢红包数据
  async loadGrabCoupons() {
    try {
      await this.loadPlatformCoupons()
      await this.loadStoreCoupons()
    } catch (error) {
      console.error('加载抢红包数据失败:', error)
      httpErrorHandler.showErrorToast(error)
    }
  },

  // 加载平台优惠券
  async loadPlatformCoupons() {
    const mockPlatformCoupons = [
      {
        id: 4,
        name: '新年红包',
        description: '新年特惠，全平台通用',
        amount: 20,
        minAmount: 100,
        totalCount: 1000,
        claimedCount: 856,
        storeId: null,
        validFrom: new Date(),
        validTo: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
      },
      {
        id: 5,
        name: '周末特惠',
        description: '周末专享优惠券',
        amount: 15,
        minAmount: 80,
        totalCount: 500,
        claimedCount: 234,
        storeId: null,
        validFrom: new Date(),
        validTo: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
      }
    ]
    
    // 计算进度百分比
    const processedPlatformCoupons = mockPlatformCoupons.map(item => ({
      ...item,
      progressPercent: ((item.claimedCount / item.totalCount) * 100).toFixed(1)
    }))
    
    this.setData({ platformCoupons: processedPlatformCoupons })
  },

  // 加载店铺优惠券
  async loadStoreCoupons() {
    const mockStoresWithCoupons = [
      {
        storeId: 1,
        expanded: false,
        store: {
          id: 1,
          name: '麦当劳(王府井店)',
          avatarUrl: '/images/stores/mcdonalds.jpg'
        },
        coupons: [
          {
            id: 6,
            name: '麦当劳满减券',
            description: '限麦当劳使用',
            amount: 8,
            minAmount: 40,
            totalCount: 200,
            claimedCount: 156,
            storeId: 1,
            validFrom: new Date(),
            validTo: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000)
          }
        ]
      }
    ]
    
    this.setData({ storesWithCoupons: mockStoresWithCoupons })
  },

  // 筛选优惠券
  filterCoupons(e) {
    const status = e.currentTarget.dataset.status
    this.setData({ 
      couponStatus: status,
      myCoupons: this.filterMyCoupons(this.data.allMyCoupons, status)
    })
  },

  // 过滤我的优惠券
  filterMyCoupons(coupons, status) {
    const now = new Date()
    
    return coupons.filter(item => {
      const isExpired = new Date(item.coupon.validTo) < now
      
      switch (status) {
        case 'unused':
          return item.status === 'UNUSED' && !isExpired
        case 'used':
          return item.status === 'USED'
        case 'expired':
          return isExpired || item.status === 'EXPIRED'
        default:
          return true
      }
    }).map(item => ({
      ...item,
      expired: new Date(item.coupon.validTo) < now
    }))
  },

  // 使用优惠券
  useCoupon(e) {
    const coupon = e.currentTarget.dataset.coupon
    wx.showToast({
      title: '请在订单中使用',
      icon: 'none'
    })
    
    // 跳转到首页选择店铺
    setTimeout(() => {
      wx.switchTab({
        url: '/pages/index/index'
      })
    }, 1500)
  },

  // 抢红包
  async grabCoupon(e) {
    const coupon = e.currentTarget.dataset.coupon
    
    if (coupon.claimedCount >= coupon.totalCount) {
      wx.showToast({
        title: '红包已抢完',
        icon: 'none'
      })
      return
    }
    
    try {
      wx.showLoading({ title: '抢夺中...' })
      
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 更新抢夺数量
      this.updateCouponCount(coupon.id)
      
      // 添加到我的优惠券
      this.addToMyCoupons(coupon)
      
      wx.hideLoading()
      
      this.setData({
        showSuccessModal: true,
        grabbedCoupon: coupon
      })
      
    } catch (error) {
      console.error('抢红包失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '抢夺失败，请重试',
        icon: 'none'
      })
    }
  },

  // 添加到我的优惠券
  addToMyCoupons(coupon) {
    const newCoupon = {
      id: Date.now(),
      userId: 1,
      couponId: coupon.id,
      status: 'UNUSED',
      claimedAt: new Date(),
      expired: false,
      coupon: {
        ...coupon,
        storeName: coupon.storeId ? '指定商家' : '全平台通用'
      }
    }
    
    // 添加到本地存储
    const localCoupons = wx.getStorageSync('myCoupons') || []
    localCoupons.unshift(newCoupon)
    wx.setStorageSync('myCoupons', localCoupons)
    
    console.log('优惠券已添加到我的优惠券')
  },

  // 更新抢夺数量
  updateCouponCount(couponId) {
    // 更新平台优惠券
    const platformCoupons = this.data.platformCoupons.map(item => {
      if (item.id === couponId) {
        const newClaimedCount = item.claimedCount + 1
        return {
          ...item,
          claimedCount: newClaimedCount,
          progressPercent: ((newClaimedCount / item.totalCount) * 100).toFixed(1)
        }
      }
      return item
    })
    
    // 更新店铺优惠券
    const storesWithCoupons = this.data.storesWithCoupons.map(store => ({
      ...store,
      coupons: store.coupons.map(coupon => {
        if (coupon.id === couponId) {
          const newClaimedCount = coupon.claimedCount + 1
          return {
            ...coupon,
            claimedCount: newClaimedCount,
            progressPercent: ((newClaimedCount / coupon.totalCount) * 100).toFixed(1)
          }
        }
        return coupon
      })
    }))
    
    this.setData({
      platformCoupons,
      storesWithCoupons
    })
  },

  // 切换店铺展开状态
  toggleStore(e) {
    const storeId = e.currentTarget.dataset.storeId
    const storesWithCoupons = this.data.storesWithCoupons.map(store => {
      if (store.storeId === storeId) {
        return { ...store, expanded: !store.expanded }
      }
      return store
    })
    
    this.setData({ storesWithCoupons })
  },

  // 隐藏成功弹窗
  hideSuccessModal() {
    this.setData({ showSuccessModal: false })
  },

  // 阻止事件冒泡
  stopPropagation() {},

  // 格式化日期
  formatDate(date) {
    return formatTime(date)
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '领取专属优惠券',
      path: '/pages/coupon/coupon?tab=grab'
    }
  }
}) 